package net.moonbiter.ebs.protocols.httpparams;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.moonbiter.OperationFailureException;
import net.moonbiter.ebs.callers.InputInterpreter;
import net.moonbiter.ebs.protocols.httpparams.tree.Tree;
import net.moonbiter.ebs.protocols.httpparams.tree.building.HttpTreeBuilder;
import net.moonbiter.ebs.protocols.httpparams.tree.interp.TreeInterpreter;
import net.moonbiter.ebs.protocols.httpparams.tree.interp.TreeInterpreterImpl;
import net.moonbiter.ebs.validation.ValidationException;

public class HttpParamsInputInterpreter implements InputInterpreter<HttpServletRequest>{
	private TreeInterpreter treeInterpeter;
	private HttpTreeBuilder httpTreeBuilder;
	private File tmpDir;

	public HttpParamsInputInterpreter(File tmpDirectoryValue, int sizeThresholdValue,
			int maxSize) {
		treeInterpeter = new TreeInterpreterImpl();
		httpTreeBuilder = new HttpTreeBuilder(tmpDirectoryValue,
				sizeThresholdValue, maxSize);
		tmpDir = tmpDirectoryValue;
	}

	public Map<String, Object> obtainParams(HttpServletRequest request,
			Map<String, Class<?>> requiredLogicalParams)
			throws OperationFailureException, ValidationException  {
		Tree tree = httpTreeBuilder.buildTree(request);

		Map<String, Object> values = new HashMap<String, Object>();
		for (String paramLogicalName : requiredLogicalParams.keySet()) {
			Class<?> logicalParamType = requiredLogicalParams
					.get(paramLogicalName);
			Object paramValue = treeInterpeter.interpret(tree,
					paramLogicalName, logicalParamType);
			values.put(paramLogicalName, paramValue);
		}
		return values;
	}
	
	public void release(){
		// TODO verify delete also if files are contained
		tmpDir.delete();
	}
}
